import cv2
import os

cam = cv2.VideoCapture(0)  # 获取摄像头
cam.set(3, 640)  # set video width  # 设置视频的高度和宽度
cam.set(4, 480)  # set video height

# 检测人脸
face_detector = cv2.CascadeClassifier('/Users/Shared/Previously Relocated Items/Security/Work/code_mrk/shumeipai/opencv/haarcascade/haarcascade_frontalface_default.xml')
# face_detector = cv2.CascadeClassifier('/home/pi/kratos/test/shumeipai/opencv/haarcascade/haarcascade_frontalface_default.xml')

# For each person, enter one numeric face id
face_id = input('\n enter user id end press <return> ==>  ')

# print("\n [INFO] Initializing face capture. Look the camera and wait ...")
# Initialize individual sampling face count
count = 0
cv2.namedWindow('FaceDetect', flags=cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO | cv2.WINDOW_GUI_EXPANDED)

while (True):
    ret, img = cam.read()
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)  # 转化为灰度图
    faces = face_detector.detectMultiScale(gray, 1.3, 5)  # 识别人脸

    count += 1
    # 在人脸上画矩形
    for (x, y, w, h) in faces:
        cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)

        cv2.imwrite("/Users/Shared/Previously Relocated Items/Security/Work/code_mrk/shumeipai/opencv/image/." + str(face_id) + '.' + str(count) + ".jpg", gray[y:y + h, x:x + w])
        # cv2.imwrite("/home/pi/kratos/test/shumeipai/opencv/image/." + str(face_id) + '.' + str(count) + ".jpg", gray[y:y + h, x:x + w])
        cv2.imshow('image', img)  # 显示

    k = cv2.waitKey(100) & 0xff
    if k == 27:
        break
    elif count >= 1000:
        break

print("\n [INFO] Exiting Program and cleanup stuff")
cam.release()
cv2.destroyAllWindows()
